export async function findAndClickElementByText(page, selector, textToFind, timeout = 30000) {
  try {
    await waitForSelector(page, selector, textToFind, timeout);

    const clicked = await page.$$eval(selector, (elements, text) => {
      const el = elements.find(e => e.textContent.trim() === text);
      if (el) {
        el.click();
        return true;
      }
      return false;
    }, textToFind);

    if (!clicked) {
      throw new Error(`Element with text "${textToFind}" not found within "${selector}"`);
    }

  } catch (error) {
    console.error(`Error clicking element with text "${textToFind}" within selector "${selector}":`, error);
    throw error;
  }
}

export async function waitForSelector(page, selector, textToFind, timeout = 30000, interval = 1000) {
  let elapsedTime = 0;

  // 每隔一段时间检查一次，直到文本加载完成或者超时
  while (elapsedTime < timeout) {
    const isSelectorFound = await page.$$eval(selector, (elements, text) => {
      const el = elements.find(e => e.textContent.trim() === text);
      return !!el;
    }, textToFind);

    if (isSelectorFound) return true;

    // 等待一段时间后继续检查
    await new Promise(resolve => setTimeout(resolve, interval));

    elapsedTime += interval;
  }

  // 超时后抛出错误
  throw new Error(`Text "${textToFind}" not found within "${selector}" after ${timeout}ms`);
}

export async function clickFormItemContent(page, labelText) {
  // 获取所有的 .el-form-item 元素
  const formItems = await page.$$('.el-form-item');

  // 遍历所有 .el-form-item 元素
  for (let formItem of formItems) {
    // 获取 label 元素
    const label = await formItem.$('label.el-form-item__label');

    if (label) {
      const labelTextContent = await page.evaluate(el => el.textContent.trim(), label);

      if (labelTextContent === labelText) {
        const content = await formItem.$('.el-form-item__content');
        if (content) {
          await content.click();
          return true;
        }
      }
    }
  }

  throw new Error(`Could not find label with text "${labelText}" and corresponding .el-form-item__content.`);
}

export async function findLabelAndInputText(page, labelText, inputValue) {
  const formItems = await page.$$('.el-form-item');

  for (let formItem of formItems) {
    const label = await formItem.$('label.el-form-item__label');

    if (label) {
      const labelTextContent = await page.evaluate(el => el.textContent.trim(), label);

      if (labelTextContent === labelText && labelText === '性别：') {
        const radios = await formItem.$$('.el-radio-group label.el-radio');

        for (let radio of radios) {
          const radioLabel = await radio.$('span.el-radio__label');
          const radioLabelText = await page.evaluate(el => el.textContent.trim(), radioLabel);

          if (radioLabelText === inputValue) {
            await radio.click();
            return true;
          }
        }
      } else if (labelTextContent === labelText && labelText === '有效期限：') {
        const inputs = await formItem.$$('input.el-input__inner');

        if (inputs.length === 2) {
          await inputs[0].press('Backspace'); // 清空输入框
          await inputs[0].type(inputValue[0]); // 输入第一个值
          await inputs[1].press('Backspace'); // 清空输入框
          await inputs[1].type(inputValue[1]); // 输入第二个值


          return true;
        } else {
          throw new Error('Did not find exactly two input fields');
        }
      } else if (labelTextContent === labelText && labelText === '球队职务（必填）：') {
        // 查找兄弟元素中的 input 框 (下拉框)
        const selectInput = await formItem.$('input.el-input__inner[readonly]');

        if (selectInput) {
          // 点击下拉框，显示下拉选项
          await selectInput.click();

          // 等待下拉菜单显示
          await new Promise(resolve => setTimeout(resolve, 2000));
          await page.waitForSelector('.el-select-dropdown__item');

          // 获取所有下拉菜单项
          const dropdownItems = await page.$$('.el-select-dropdown__item');

          for (let item of dropdownItems) {
            // 获取每个下拉选项的文本内容
            const itemText = await page.evaluate(el => el.textContent.trim(), item);
            // 如果选项与传入的 inputValue 匹配
            if (itemText === inputValue) {
              // 点击对应的选项
              await item.click();
              return true; // 成功选择后返回
            }
          }

          // 如果没有找到匹配的选项，抛出错误
          throw new Error(`Could not find dropdown option with text "${inputValue}"`);
        } else {
          throw new Error('Could not find the select input element');
        }
      }
      else if (labelTextContent === labelText) {
        const inputElement = await formItem.$('.el-form-item__content input.el-input__inner');

        if (inputElement) {
          await inputElement.type(inputValue);
          return true;
        }
      }
    }
  }

  // 如果没有找到匹配的 label 或者 input
  throw new Error(`Could not find label with text "${labelText}" and corresponding input.`);
}
